package org.rency.common.utils.security;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.CharEncoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 
* @ClassName: BASE64Utils 
* @Description: BASE64Utils加密解密算法
* @Author user_rcy@163.com
* @Date 2015年3月8日 下午9:52:20 
*
 */
@SuppressWarnings("restriction")
public class Base64Utils {
	
	private static final Logger logger = LoggerFactory.getLogger(Base64Utils.class);
	
	private final static String CHARSET = "UTF-8";
	private static BASE64Encoder encoder = new BASE64Encoder(); 
	
	private static BASE64Decoder decoder = new BASE64Decoder(); 
	
	/**
	 * BASE64解码
	 * </br>Created on 2016年4月26日
	 * @param content
	 * @return
	 * @throws IOException
	 */
	public static String decoder(String content) throws IOException{
		String s = new String(decoder.decodeBuffer(content));
        logger.debug("Base64 decoder{} ->{} ",content,s);
        return s;
	}
	
	/**
	 * BASE64编码
	 * </br>Created on 2016年4月26日
	 * @param content
	 * @return
	 */
	public static String encoder(String content){
		try {
			byte[] b = content.getBytes(CHARSET);
			return encoder(b);
		} catch (UnsupportedEncodingException e) {
			logger.error("Base64Utils 转码异常.",e);
			return null;
		}  
         
	}
	
	/**
	 * BASE64编码
	 * </br>Created on 2016年4月26日
	 * @param content
	 * @return
	 */
	public static String encoder(byte[] content){
		String s = encoder.encodeBuffer(content);
        logger.debug("Base64 encoder{} ->{} ",content,s);
        return s; 
	}
	
	
	public static String encodeBase64String(byte[] binaryData) {
        byte[] bytes = Base64.encodeBase64(binaryData);
        if (bytes == null) {
            return null;
        }
        try {
            return new String(bytes, CharEncoding.UTF_8);
        } catch (UnsupportedEncodingException ex) {
            return null;
        }
    }
    
    public static byte[] decodeBase64(String base64String) {
        if (base64String == null) {
            return null;
        }
        try {
            return Base64.decodeBase64(base64String.getBytes(CharEncoding.UTF_8));
        } catch (UnsupportedEncodingException ex) {
            return null;
        }
    }

    public static byte[] decodeBase64(byte[] base64Bytes) {
        if (base64Bytes == null) {
            return null;
        }
        return Base64.decodeBase64(base64Bytes);
    }
	
	public static void main(String[] args) throws IOException {
		System.out.println(encoder("rency"));
		System.out.println(decoder("cmVuY3k="));
	}
	
}